import config from './config'
import md5 from './md5'
import {
    Base64
} from './base64'
import {
    CryptoJS
} from './base64Cry'

const base64 = new Base64();

function getSimpleHeader() {
    let header = {
        'Content-Type': 'text/plain,charset=utf-8'
    }
    return header
};

function encryptData(info) {
    let jsonStr = JSON.stringify(info);
    let base64Str = base64.encode(jsonStr);
    let md5Str = md5(jsonStr);
    let str = md5Str + "," + base64Str;
    return str;
}

function decryptResponse(str) {
    let arr = str.split(',');
    let md5Str = arr[0];
    let base64Str = arr[1];
    let jsonStr = base64.decode(base64Str);
    let obj = JSON.parse(jsonStr);
    return obj;
}

function showNetworkError() {
    wx.showModal({
        title: '错误',
        content: '无法连接服务器',
        showCancel: false
    })
}
export default {
    sendLogin: (code) => {
        return new Promise((resolve, reject) => {
            let info = {
                code: code
            }
            let str = encryptData(info);
            wx.request({
                url: config.baseUrl + 'pakj/wexin/miniProgramLogin',
                method: "POST",
                dataType: "text",
                responseType: "text",
                data: str,
                header: getSimpleHeader(),
                success: (res) => {
                    if (res.statusCode === 200) {
                        let meg = decryptResponse(res.data);
                        resolve(meg);
                    } else {
                        showNetworkError();
                        reject(new Error("Net work Error"))
                    }
                },
                fail: (res) => {
                    showNetworkError();
                    reject(new Error("Net work Error2"))
                }
            });
        })
    },
    sendEncryPhone: (info, callback) => {
        let str = encryptData(info);
        wx.request({
            url: config.baseUrl + 'pakj/wexin/toEncryData',
            method: "POST",
            dataType: "text",
            responseType: "text",
            data: str,
            header: getSimpleHeader(),
            success: (res) => {
                if (res.statusCode === 200) {
                    let meg = decryptResponse(res.data);
                    callback(meg);
                } else {
                    showNetworkError();
                }
            },
            fail: (res) => {
                showNetworkError();
            }
        });
    }
}